<!--  -->
<template>
  <div
    :class="['product-detail',flag?'':'',tabIndex==1&&commentList.length!=0?'product-detail-h-100':'']"
  >
    <Nav title="产品详情">
      <template v-slot:left>
        <span class="back-icon" @click="$router.back()"></span>
      </template>
      <!-- <template v-slot:right>
        <span class="notice mr-18"></span>
        <span class="share"></span>
      </template>-->
    </Nav>
    <!-- 轮播图 -->
    <swiper class="swiper" :options="swiperOption" v-if="swiperSlides.length!=0">
      <swiper-slide v-for="(slide, index) in swiperSlides" :key="index">
        <img :src="slide" alt="" @click="previewImg(swiperSlides,index)">
      </swiper-slide>
      <div class="swiper-pagination" slot="pagination"></div>
    </swiper>
    <div class="swiper" v-else></div>
    <div class="product-info flex aligin-center">
      <div class="flex-1 info flex justify-between aligin-center">
        <span class="f-16 color-red">
          ￥
          <span class="ml-6 f-22 color-red f-bold">{{productData.price}}</span>
        </span>
      </div>
      <div class="rate f-12 color-white flex justify-center aligin-center" @click="share">
        <span class="share-icon"></span>
        <span>分享</span>
      </div>
    </div>
    <!-- 产品名称 -->
    <div class="product-name f-14 f-medium">{{productData.goods_name}}</div>
    <div class="other ml-16 color-gray f-12 mt-12 flex justify-between">
      <div>运费: {{productData.shipping_fee=="包邮"?productData.shipping_fee:'￥'+productData.shipping_fee}}</div>
      <!-- <div>销量: {{productData.sales}}</div> -->
      <div>库存: {{productData.stock}}</div>
    </div>
    <div class="divide-line"></div>
    <div  class="activity-info flex justify-between aligin-center" @click="toDetail">
      <span class="color-gray label">活动</span>
      <span class="flex-1">
        本商品参与
        <span class="color-red">{{productData.abbreviation}}</span>活动,即可获得
        <span class="color-red">{{productData.give_power}}</span>
        个活动号码
      </span>
      <span class="arrow-right"></span>
    </div>
    <div class="divide-line"></div>
    <template v-for="(item,index) in productData.attribute">
      <div :key="index" v-if="((productData.attribute.length-1)!=index||isFirst)">
        <div
          v-if="item.attr_value"
          class="address pl-16 flex aligin-center"
          @click="selectOption(index)"
        >
          <span class="color-gray height-100 mr-8">{{item.attr_value_name}}</span>
          <div>
            <template v-for="(_item,_index) in item.attr_value">
              <span class="ml-10 line-height-18 f-12" :key="_index">{{_item}}</span>
            </template>
          </div>
          <span class="ml-auto arrow-right mr-18" v-if="(productData.attribute.length-1)==index"></span>
        </div>
        <div class="divide-line"></div>
      </div>
      <div v-else :key="index">
        <div
          class="address pl-16 flex aligin-center"
          @click="selectOption(productData.attribute.length-1)"
        >
          <span class="color-gray height-100 mr-8">选择</span>
          <div>
            <template v-for="(_item,_index) in c_selectOption">
              <span class="ml-10 line-height-18 f-12" :key="_index">{{_item.spec_value_name}}</span>
            </template>
          </div>
          <span class="ml-auto arrow-right mr-18"></span>
        </div>
        <div class="divide-line"></div>
      </div>
    </template>
    <!-- 选择产品参数 -->
    <ProductParams
      ref="productParams"
      class="scroll-wrapper"
      :flag.sync="flag"
      type="shoppingCar"
      :is_norequiremoney="productData.is_norequiremoney"
      :m_id="productData.m_id"
      :givePower.sync="productData.give_power"
      :power.sync="productData.power"
      :current.sync="productData.current"
      :progress.sync="productData.progress"
      :productOption.sync="productOption"
      :initPic.sync="initPic"
      :c_selectOption.sync="c_selectOption"
      :sku.sync="sku"
      :limit.sync="productData.limit" 
      @submit="submit"
      @closeDialog="closeDialog"
      @addShoppingCar="addShoppingCar"
      @optionSelected="optionSelected"
    ></ProductParams>
    <div class="shop flex justify-between aligin-center">
      <img :src="productData.merchant.m_avatar||productData.shop_logo" alt="">
      <div class="ml-14 mr-auto">
        <div class="f-14">{{productData.merchant.m_nickname}}</div>
        <div class="mt-6 f-10 color-gray">{{productData.merchant.m_address}}</div>
      </div>
      <button
        class="z-btn f-12 color-white flex justify-center aligin-center"
        @click="showTel"
      >进店</button>
    </div>  
    <div class="divide-line"></div>
    <div id="tabDetail"></div>
    <div
      class="flex justify-between aligin-center"
      style=" background: #fff;"
      :class="isSticky?'sticky':''"
    >
      <div class="tab-container">
        <TabCommon :tabs.sync="tabs" :tabIndex.sync="tabIndex" v-stream:tabChange="tabChange$"></TabCommon>
      </div>
    </div>
    <div :class="isSticky?'pt-64':''" class="height-full">
      <template v-if="tabIndex==0">
        <div ref="htmlParent" class="html-parent" v-html="productData.description"></div>
      </template>
      <template v-else>
        <div class="scroll-wrap">
          <Comment :commentList.sync="observabelProductList"></Comment>
          <template v-if="productList.length!=0">
            <div class="loading-bottom mt-10 f-14" v-if="loading">加载中...</div>
            <div class="loading-bottom mt-10 f-14" v-if="noMore">没有更多了</div>
          </template>
        </div>
      </template>
    </div>
 
    <BottomBar
      v-show="!flag"
      :isCollection.sync="isCollection"
      @orderConfirm="orderConfirm"
      @toService="showTel"
    ></BottomBar>
    <div class="mask-info" v-if="showMask">
      <div class="J-weixin-tip weixin-tip">
        <div class="weixin-tip-content">请在菜单中选择分享</div>
      </div>
      <div class="btn flex justify-center aligin-center" @click="showMask=false">我知道了</div>
    </div>
  </div>
</template>

<script>
import Nav from "../../components/Nav";
import { ImagePreview } from 'vant';
import ProductParams from "../../components/ProductParams";
import {
  productDetail,
  productSku,
  orderCreate,
  productEvaluate,
  weLogin,
  cart_store
} from "../../api/api";
import TabCommon from "../../components/TabCommon";
import BottomBar from "../../components/BottomBar";
import Comment from "../../components/Comment";
import Page from "../../mixin/page";
import { fromEvent, from, merge, empty, of, concat } from "rxjs";
import {
  map,
  filter,
  exhaustMap,
  debounceTime,
  switchMap,
  throttleTime,
  tap
} from "rxjs/operators";
export default {
  mixins: [Page],
  components: { Nav, ProductParams, TabCommon, BottomBar, Comment },
  data() {
    return {
      showMask: false,
      scrollTop: "",
      productData: {merchant:{},power:10}, //产品详情
      productOption: [], //产品参数
      c_selectOption: [], //参数规格
      sku: [], //匹配规则？
      initPic: "", //初始化图片
      swiperOption: {
        loop: true,
        autoplay: true, //等同于以下设置
        pagination: {
          el: ".swiper-pagination"
        }
      }, //轮播图配置
      swiperSlides: [], //轮播图
      flag: false, //选取产品参数组件flag
      tabIndex: 0,
      isFirst: true,
      isSticky: false,
      tabs: ["宝贝详情", "宝贝评价"],
      payFlag: false, //支付flag
      isCollection: false, //是否收藏
      commentList: [] //品论列表
    };
  },
  domStreams: ["tabChange$"],
  subscriptions() {
    let subscribtion = this.initRxjs();
    return {
      observabelProductList: subscribtion
    };
  },
  computed: {},
  watch: {},
  methods: {
    previewImg(url,index) {
       console.log("url",url)
      ImagePreview({images:url,startPosition: index,});
    },
    toDetail(){
      if(this.$route.query.pid){
        this.$router.replace({name:"detail",params:{id:this.$route.params.id},query:{pid:this.$route.query.pid}})
      }
      else{
        this.$router.replace({name:"detail",params:{id:this.$route.params.id}})
      }
    },
    _shareConfig(jsk) {
  
      wx.config(jsk);
      wx.ready(() => {
        wx.updateTimelineShareData({
          title: this.productData.goods_name, // 分享标题
          link: window.location.origin+window.location.pathname + "?pid=" + this.productData.uid, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
          imgUrl: this.swiperSlides[0], // 分享图标
          success: function() {
            
          },
          fail:function(e){
          
          }
        });
        wx.updateAppMessageShareData({
          title: this.productData.goods_name, // 分享标题
          link: window.location.origin+window.location.pathname + "?pid=" + this.productData.uid, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
          desc: this.productData.share_name||"兰溪官方特色购物平台。", // 分享描述
          imgUrl: this.swiperSlides[0], // 分享图标
          success: function() {
          
          },
          fail:function(e){
            
          }
        });
      });
      wx.error(res => {
      
        // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
      });
    },
    share() {
      // 分享

      var ua = navigator.userAgent.toLowerCase();
      var isWeixin = ua.indexOf("micromessenger") != -1;
      if (isWeixin) {
        this.showMask = true;
      } else {
        this.$copyText(
         window.location.origin+window.location.pathname+ "?pid=" + this.productData.uid
        ).then(
          e => {
            this.$toast("复制成功！");
          },
          e => {
            this.$notify(e);
          }
        );
      }
    },
    showTel() {
      window.location.href = 'tel://'+this.productData.merchant.m_phone
      // this.$dialog.alert({
      //   title: "客服电话",
      //   message: this.productData.mobile
      // });
    },
    getTabTop() {
      return document.getElementById("tabDetail").offsetTop;
    },
    initRxjs() {
      //滚动事件
      let scroll = fromEvent(window, "scroll").pipe(
        //判断吸顶
        tap(() => {
          let top = document.getElementById("tabDetail").getBoundingClientRect()
            .top;
          this.isSticky = top <= 0;
        }),
        //判断是否滚动到底部
        filter(() =>
          this.isScrollEnd(document.documentElement || document.body)
        ),
        filter(() => this.tabIndex == 1),
        //判断是否还有数据未加载
        filter(this.noMoreData),
        //截流
        throttleTime(1000)
      );
      //tab 切换事件
      let tabEvent = this.tabChange$.pipe(
        //判断是否是有效切换
        filter(({ event: { msg: index } }) => {
          if (this.tabIndex != index) {
            this.tabIndex = index;
            this.current_page = 0;
            this.last_page = 1;
            this.productList = [];
            return true;
          }
          return false;
        }),
        filter(() => this.tabIndex == 1)
      );
      return merge(scroll, tabEvent).pipe(
        //替换
        switchMap(() =>
          productEvaluate({
            id: this.$route.params.productId,
            page: this.current_page + 1
          })
        ),
        map(this.execResult)
      );
    },
    addShoppingCar(productNumber, item){
      cart_store({
        activity_id:this.$route.params.id,
        goods_id:this.$route.params.productId,
        sku_id: item.sku_id,
        num:productNumber
      }).then(({data:{result}})=>{
         this.$toast(result)
         this.flag = false;
      })
    },
    // 点击预购
    submit(productNumber, item) {
      this.flag = false;
      this.payFlag = true;
      orderCreate({
        subject: this.$route.params.key,
        product_id: this.$route.params.productId,
        activity_id: this.$route.params.id,
        sku_id: item.sku_id,
        numbers: productNumber,
        device_code: 1
      })
        .then(res => {
          this.$router.push({
            name: "orderDetail",
            params: { id: res.data.result.order_no }
          });
        })
        .catch(res => {
          if (res == "请先使用微信进行授权，享用更好的服务") {
            this.$dialog
              .confirm({
                message: "请先使用微信进行授权，享用更好的服务"
              })
              .then(() => {
                return weLogin({ from: "authorization" });
              })
              .then(res => {
                window.location.href = res.data.result;
              });
          }
        });
    },
    tabChange(index) {
      if (this.tabIndex != index) {
        this.tabIndex = index;
        //重置
        this.current_page = 0;
        this.last_page = 1;
        this.loading = false;
        this.commentList = [];
        this._api();
      }
    },
    // 关闭产品规格对话框
    closeDialog() {
      this.flag = false;
    },
    //我要预约
    orderConfirm() {
      if (this.isFirst) {
        this.selectOption(this.productData.attribute.length - 1);
      } else {
        let itemData = this.$refs.productParams.c_sku;
        orderCreate({
          subject: this.$route.params.key,
          product_id: this.$route.params.productId,
          activity_id: this.$route.params.id,
          sku_id: itemData.sku_id,
          numbers: this.$refs.productParams.productNumber,
          device_code: 1
        })
          .then(res => {
            this.$router.push({
              name: "orderDetail",
              params: { id: res.data.result.order_no }
            });
          })
          .catch(res => {
            if (res == "请先使用微信进行授权，享用更好的服务") {
              this.$dialog
                .confirm({
                  message: "请先使用微信进行授权，享用更好的服务"
                })
                .then(() => {
                  return weLogin({ from: "authorization" });
                })
                .then(res => {
                  window.location.href = res.data.result;
                });
            }
          });
      }
    },
    //弹出产品规格对话框
    selectOption(index) {
      if (this.productData.attribute.length - 1 != index) {
        return;
      }
      productSku({ id: this.$route.params.productId }).then(res => {
        this.productOption = res.data.result.spec;
        this.sku = res.data.result.sku;
        let data = res.data.result.spec.map(item => {
          return item.value[0];
        });
        this.c_selectOption = data;
        this.flag = true;
      });
    },
    //选择规格
    optionSelected(item) {
      //设置单选
      let index = this.c_selectOption.findIndex(_item => {
        return _item.spec_id == item.spec_id;
      });
      if (index != -1) {
        this.c_selectOption.splice(index, 1, item);
      }
    }
  },
  created() {},
  mounted() {
    productDetail({
      id: this.$route.params.productId,
      key: this.$route.params.key
    }).then(({ data: { result } }) => {
      this.productData = result;
      this.initPic = result.pic_cover_small;
      this.swiperSlides = result.swiper_imgs;
    
      const regex = new RegExp("<img", "gi");
      this.$set(
        this.productData,
        "description",
        result.description.replace(
          regex,
          `<img style="max-width: 100%; height: auto;display:block"`
        )
      );
      this.$nextTick(() => {
        this.scrollTop = this.getTabTop();
      });
       //微信分享配置
      if (typeof wx !="undefined") {
            this._shareConfig(result.jsk);
      }
    });
  },
  updated() {}, //生命周期 - 更新之后
  destroyed() {
    window.onscroll = null;
    clearTimeout(this.loadMoreTimer);
    this.loadMoreTimer = null;
  } //生命周期 - 销毁完成
};
</script>
<style lang='less' scoped>
@import url("../../assets/style/mixin"); //引入公共css类

.product-detail /deep/ .swiper-pagination-bullet {
  border-radius: 50%;
  width: 5px;
  height: 5px;
  background: #b6b6b7;
  transition: all 0.3s ease;
}
.product-detail /deep/ .swiper-pagination-bullet-active {
  width: 23px;
  height: 5px;
  border-radius: 3px;
  .bg-1();
}
.pt-64 {
  padding-top: 64px;
}
.height-full {
  padding-bottom: 50px;
  background: #fff;
  min-height: calc(100% - 64px);
}
.sticky {
  position: fixed;
  top: 0;
  height: 64px;
  width: 100%;
  background: #fff;
  z-index: 100;
}
.color-white {
  color: #fff;
}
.product-detail-h-100 {
  height: 100%;
}
.tab-container {
  padding: 10px 10px;
  width: 50%;
}
.product-detail {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  padding-bottom: 60px;
  height: 100%;
  box-sizing: border-box;
  background: #fff;
  z-index: 400;
  .activity-info {
    padding: 11px 12px;
    font-size: 12px;
    line-height: 16px;
    .flex-1{
      flex:1;
    }
    .label{
      width: 50px;
      flex-shrink: 0;
    }
    .color-red {
      color: #cc0000;
    }
    .arrow-right {
      flex-shrink: 0;
    height: 12px;
    width: 12px;
    .bg-image("../../assets/imgs/arrow-right-b");
    background-size: 100% 100%;
  }
  }
  .back-icon {
    display: inline-block;
    width: 16px;
    height: 16px;
    .bg-image("../../assets/imgs/back");
    background-size: 100% 100%;
  }
  .notice {
    display: inline-block;
    width: 17px;
    height: 17px;
    .bg-image("../../assets/imgs/notice");
    background-size: 100% 100%;
  }
  .share {
    display: inline-block;
    width: 17px;
    height: 17px;
    .bg-image("../../assets/imgs/share-product");
    background-size: 100% 100%;
  }
  .swiper {
    height: 375px;
    img {
      display: block;
      height: 100%;
      width: 100%;
      &::after {
        display: none;
      }
    }
  }
  .product-info {
    height: 35px;
    .info {
      padding: 0 22px 0 17px;
      height: 100%;
    }
    .f-16 {
      font-size: 16px;
      font-weight: 500;
    }
    .rate {
      width: 67px;
      height: 23px;
      border-top-left-radius: 10px;
      border-bottom-left-radius: 10px;
      .bg-1();
      .share-icon {
        margin-right: 4px;
        width: 16px;
        height: 14px;
        background: url("../../assets/imgs/share-icon.png");
        background-size: 100% 100%;
      }
    }
  }
  .other {
    padding-bottom: 14px;
    width: 306px;
  }
  .product-name {
    padding: 7px 17px 0;
    line-height: 19px;
  }
  .address {
    padding: 12px 12px;
    .height-100 {
      width: 30px;
      height: 100%;
    }
    .line-height-18 {
      line-height: 18px;
    }
  }
  .arrow-right {
    height: 12px;
    width: 12px;
    .bg-image("../../assets/imgs/arrow-right-b");
    background-size: 100% 100%;
  }
  .shop {
    padding: 0 16px;
    height: 59px;
    background: #fff;
    img {
      flex-shrink: 0;
      height: 40px;
      width: 40px;
      border-radius: 50%;
    }
    .z-btn {
      flex-shrink: 0;
      height: 25px;
      width: 55px;
      .bg-1();
    }
  }

  .scroll-wrap {
    padding-bottom: 49px;
    height: calc(100% - 60px);
    overflow: hidden;
  }
  .loading-bottom {
    width: 100%;
    text-align: center;
  }
}
.modal-open {
  position: fixed;
  width: 100%;
}
.mask-info {
  position: fixed;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  background: rgba(0, 0, 0, 0.6);
  z-index: 600;
}
.btn {
  color: #fff;
  margin: 10px auto;
  width: 70px;
  height: 25px;
  border-radius: 5px;
  border: 1px dashed #fff;
}
.weixin-tip-content {
  font-size: 16px;
  letter-spacing: 5px;
  font-weight: bold;
  line-height: 20px;
}
.weixin-tip {
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  color: #fff;
  width: 265px;
  padding: 55px 0 0;
  margin: 0 auto;
  text-align: center;
  background: url()
    no-repeat right top;
  background-size: 45px 68px;
}

.weixin-tip-img {
  padding: 110px 0 0;
}

.weixin-tip-img::after {
  display: block;
  margin: 15px auto;
  content: " ";
  background-size: cover;
}
</style>